﻿using WCS.Entity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using WcsApi.Models;
using WCSApi;
using SqlSugar;
using System.Reflection;
using API.SqlSugar;

namespace WcsApi.Controllers
{
    /// <summary>
    /// 任务控制器
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiExplorerSettings(GroupName = "1")]
    [ApiController]
    public class MESController : Controller
    {
        static SqlSugarDapper _sqlSugarDapper = SqlSugarDapper.GetDbContext();

        private readonly MyDbContext _commonDbContext;

        IBase _wCSImpl = new WCSImpl();

        public MESController(MyDbContext commonDbContext)
        {
            _commonDbContext = commonDbContext;
        }

        /// <summary>
        /// 铸造站台修改生产产品信息
        /// </summary>
        /// <param name="sandCoreOffline">任务对象</param>
        /// <returns></returns>
        [HttpPost]
        public Result<object> ChangeMaterial(ChangeMaterial changeMaterial)
        {
            try
            {
                _sqlSugarDapper.DB.Updateable<WcsDevStation>()
                    .SetColumns(s => s.ProductionMaterials == changeMaterial.materialNo)
                    .Where(w => w.Station_Plc_No == changeMaterial.station)
                    .ExecuteCommand();
                 
                var result = Result<object>.success();

                // 记录接口请求返回信息
                _sqlSugarDapper.DB.Insertable(new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}       (铸造站台修改生产产品信息)",
                    JsonConvert.SerializeObject(changeMaterial),
                    JsonConvert.SerializeObject(result)
                    )).ExecuteCommand();

                return result;
            }
            catch (Exception ex)
            {
                var result = Result<object>.error(ex.Message);

                _sqlSugarDapper.DB.Insertable(new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}       (铸造站台修改生产产品信息)出现异常",
                    JsonConvert.SerializeObject(changeMaterial),
                    JsonConvert.SerializeObject(result)
                )).ExecuteCommand();

                return result;
            }
        }

        /// <summary>
        /// 砂芯下线
        /// </summary>
        /// <param name="sandCoreOffline">任务对象</param>
        /// <returns></returns>
        [HttpPost]
        public Result SandCoreOffline(SandCoreOffline sandCoreOffline)
        {
            try
            {
                WcsTaskMain wcsTaskMain = new WcsTaskMain()
                {
                    Task_Type = "in",
                    TrayBar_Code = "111111", // 托盘号
                    MaterialType = sandCoreOffline.materialNo,// 物料号
                    Start_Station = sandCoreOffline.station,// 站台号
                    End_Station = "A001",
                    ProcessType = ProcessType.砂芯下线到入库口到缓存区.ToString(),
                    QualityTesting = sandCoreOffline.qualityTesting,
                    Current_Station = sandCoreOffline.station,
                    ContinueProduction = sandCoreOffline.continueProduction,
                };

                _sqlSugarDapper.DB.Insertable(wcsTaskMain).ExecuteCommand();

                var result = new Result { code = 1};

                // 记录接口请求返回信息
                ApiLogs apiLog = new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}       (MES给WCS下发任务)",
                    JsonConvert.SerializeObject(sandCoreOffline),
                    JsonConvert.SerializeObject(result));

                _sqlSugarDapper.DB.Insertable(apiLog).ExecuteCommand();

                return result;
            }
            catch (Exception ex)
            {
                var result = Result<object>.error(ex.Message);

                _sqlSugarDapper.DB.Insertable(new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}       (MES给WCS下发任务)出现异常",
                    JsonConvert.SerializeObject(sandCoreOffline),
                    JsonConvert.SerializeObject(result)
                )).ExecuteCommand();

                return null;
            }
        }

        /// <summary>
        /// 砂芯开始生产
        /// </summary>
        /// <param name="mesSendTask">任务对象</param>
        /// <returns></returns>
        [HttpPost]
        public Result<object> StartProduction(MesSendTask mesSendTask)
        {
            try
            {
                var ExStation = _sqlSugarDapper.DB.Queryable<CallMaterial>().ToList().Find(f => f.CallStation == mesSendTask.Station);
                if (ExStation != null)
                {
                    return Result<object>.error("该站台已有申请记录，不能重复申请");
                }

                _sqlSugarDapper.DB.Insertable(new CallMaterial { CallStation = mesSendTask.Station, MaterialType = mesSendTask.MaterialNo }).ExecuteCommand();

                var station = (Convert.ToInt32(mesSendTask.Station) + 4).ToString();

                _sqlSugarDapper.DB.Insertable(new CallMaterial { CallStation = station, MaterialType = mesSendTask.MaterialNo }).ExecuteCommand();

                var result = Result<object>.success();
                // 记录接口请求返回信息
                _sqlSugarDapper.DB.Insertable(new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}       (PDA下发任务)",
                    JsonConvert.SerializeObject(mesSendTask),
                    JsonConvert.SerializeObject(result)
                    )).ExecuteCommand();

                return result;
            }
            catch (Exception ex)
            {
                var result = Result<object>.error(ex.Message);

                _sqlSugarDapper.DB.Insertable(new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}       (MES给WCS下发任务)出现异常",
                    JsonConvert.SerializeObject(mesSendTask),
                    JsonConvert.SerializeObject(result)
                )).ExecuteCommand();

                return result;
            }
        }

        /// <summary>
        /// WMS给WCS下发任务
        /// </summary>
        /// <param name="wmsSendTask">任务对象</param>
        /// <returns></returns>
        [HttpPost]
        public Result<WcsTaskMain> GetWCSTaks()
        {
            try
            {
                var data = _wCSImpl.Get<WcsTaskMain>();

                var result = Result<WcsTaskMain>.success(data);
                return result;
            }
            catch (Exception ex)
            {

                return null;
            }
        }
    }

    public class Result
    {
        public int code { get; set; }

        public string message { get; set; }
    }


    public class WCSImpl : IBase
    {
        static SqlSugarDapper _sqlSugarDapper = SqlSugarDapper.GetDbContext();
        public List<T> Get<T>()
        {
            var data = _sqlSugarDapper.DB.Queryable<T>().ToList();

            return data;
        }
    }

    public interface IWCSImpl : IBase
    {
    }

    public interface IBase
    {
        List<T> Get<T>();
    }
}